<?php
namespace app\admin\controller;
use think\Request;
use app\common\model\BackendMenuModel;
use app\common\controller\Backend;

class Menu extends Backend
{
  public function index()
  {
  	$BackendMenuModel = new BackendMenuModel();
  	$menuList = $BackendMenuModel->getMenuAarray();
  	// dump( $menuList );die();

    return view('index',['menuList'=>$menuList]);
  }

  //添加
  public function create(Request $request = null){
    if(Request::instance()->isPost()){
      $post = $request->post();
      $BackendMenuModel = new BackendMenuModel();
      $result = $BackendMenuModel->allowField(true)->validate(true)->save($post);
      if(false === $result){
        // 验证失败 输出错误信息
        $this->error($BackendMenuModel->getError());
      }else{

        $this->success("成功！");
      }
      
    }else{
    	//获取菜单
    	$BackendMenuModel = new BackendMenuModel();
    	$menuList = $BackendMenuModel->getMenuList();

      return view("create",['menuList'=> $menuList]);
    }
  }


  //编辑
  public function update(Request $request = null){
    if(Request::instance()->isPost()){
      $post = $request->post();
      $BackendMenuModel = new BackendMenuModel();
      $result = $BackendMenuModel->allowField(true)->validate(true)->save($post, $post['id']);
      if(false === $result){
        // 验证失败 输出错误信息
        $this->error($BackendMenuModel->getError());
      }else{

        $this->success("成功！");
      }
      
    }else{
    	$id = $request->get("id/d");
    	//获取菜单
    	$BackendMenuModel = new BackendMenuModel();
    	$menuList = $BackendMenuModel->getMenuList();

    	//获取当前菜单
    	$menuModel = $BackendMenuModel->getMenuById($id);

      return view("update",['menuList'=> $menuList,'menuModel'=>$menuModel]);
    }
  }

  //删除
  public function deleteAll(Request $request = null){
  	$id = $request->post("id/d");
  	$BackendMenuModel = new BackendMenuModel();
  	//判断该菜单下是否有分类
  	if($BackendMenuModel->isChildren($id)){
  		return json(['status'=>400,'msg'=>'请先去删除子分类！']);
  	}

		if($BackendMenuModel->deleteAll($id) > 0){
			return json(['status'=>200,'msg'=>'成功']);
		}else{
			return json(['status'=>400,'msg'=>'失败']);
		}
  }


  //改变排序
  public function changeSalt(Request $request = null){
    $param = $request->param();
    $BackendMenuModel = new BackendMenuModel();
    if($BackendMenuModel->changeSalt($param['id'], $param['sort']) > 0){
      return json(['status'=>200,'msg'=>'成功']);
    }else{
      return json(['status'=>400,'msg'=>'失败']);
    }
  }
}

